package Dao.Impl;

import Dao.KnowledgeBaseDAO;
import entity.KnowledgeBase;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/4/28 21:50
 * @Version 1.0 （版本号）
 */
public class KnowledgeBaseDAOImpl implements KnowledgeBaseDAO {
    private final Connection connection;

    public KnowledgeBaseDAOImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public KnowledgeBase create(KnowledgeBase knowledgeBase) throws SQLException {
        String sql = "INSERT INTO knowledge_base (name, description, creator_id, access_level) VALUES (?, ?, ?, ?)";
        try (PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            stmt.setString(1, knowledgeBase.getName());
            stmt.setString(2, knowledgeBase.getDescription());
            stmt.setInt(3, knowledgeBase.getCreatorId());
            stmt.setString(4, knowledgeBase.getAccessLevel().name());

            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("创建知识库失败");
            }

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    knowledgeBase.setId(generatedKeys.getInt(1));
                    return knowledgeBase;
                }
            }

            throw new SQLException("创建知识库失败，无法获取ID");
        }
    }

    @Override
    public boolean update(KnowledgeBase knowledgeBase) throws SQLException {
        String sql = "UPDATE knowledge_base SET name = ?, description = ?, access_level = ?, updated_at = NOW() WHERE id = ? AND creator_id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, knowledgeBase.getName());
            stmt.setString(2, knowledgeBase.getDescription());
            stmt.setString(3, knowledgeBase.getAccessLevel().name());
            stmt.setInt(4, knowledgeBase.getId());
            stmt.setInt(5, knowledgeBase.getCreatorId());

            return stmt.executeUpdate() > 0;
        }
    }

    @Override
    public boolean delete(int knowledgeBaseId, int creatorId) throws SQLException {
        String sql = "DELETE FROM knowledge_base WHERE id = ? AND creator_id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, knowledgeBaseId);
            stmt.setInt(2, creatorId);
            return stmt.executeUpdate() > 0;
        }
    }

    @Override
    public KnowledgeBase findById(int knowledgeBaseId) throws SQLException {
        String sql = "SELECT id, name, description, creator_id, created_at, updated_at, access_level FROM knowledge_base WHERE id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, knowledgeBaseId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return new KnowledgeBase(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("description"),
                        rs.getInt("creator_id"),
                        rs.getDate("created_at"),
                        rs.getDate("updated_at"),
                        KnowledgeBase.AccessLevel.valueOf(rs.getString("access_level"))
                );
            }
            return null;
        }
    }

    @Override
    public List<KnowledgeBase> findByCreator(int creatorId) throws SQLException {
        List<KnowledgeBase> result = new ArrayList<>();
        String sql = "SELECT id, name, description, creator_id, created_at, updated_at, access_level FROM knowledge_base WHERE creator_id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, creatorId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                result.add(new KnowledgeBase(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("description"),
                        rs.getInt("creator_id"),
                        rs.getDate("created_at"),
                        rs.getDate("updated_at"),
                        KnowledgeBase.AccessLevel.valueOf(rs.getString("access_level"))
                ));
            }
        }
        return result;
    }

    @Override
    public List<KnowledgeBase> findAccessibleByUser(int userId) throws SQLException {
        List<KnowledgeBase> result = new ArrayList<>();
        String sql = "SELECT DISTINCT kb.id, kb.name, kb.description, kb.creator_id, kb.created_at, kb.updated_at, kb.access_level " +
                "FROM knowledge_base kb LEFT JOIN knowledge_base_member kbm ON kb.id = kbm.knowledge_base_id " +
                "WHERE kb.creator_id = ? OR kbm.user_id = ? order by kb.created_at desc ";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            stmt.setInt(2, userId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                result.add(new KnowledgeBase(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("description"),
                        rs.getInt("creator_id"),
                        rs.getDate("created_at"),
                        rs.getDate("updated_at"),
                        KnowledgeBase.AccessLevel.valueOf(rs.getString("access_level"))
                ));
            }
        }
        return result;
    }
}
